package com.example.demo.controller;

/**
 * Created by zouwenchang on 2018/1/18.
 */

import com.alibaba.fastjson.JSON;
import com.example.demo.model.fileNameModel;
import com.example.demo.utils.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("/test")
public class uploadController {

    @GetMapping(value="/greeting")

    public String greeting(HttpServletRequest request, HttpServletResponse response) {
        System.out.println(request.getHeader("JSESSOINID"));

        return "greeting";
    }
    @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public String goUploadImg() {
        //跳转到 templates 目录下的 uploadimg.html
        return "uploadimg";
    }

    @CrossOrigin(origins = "*", allowedHeaders = "*", allowCredentials = "true")
    //处理文件上传
    @PostMapping(value="/testuploadimg")
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,
                                          HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);

        String fileName = file.getOriginalFilename();
        fileNameModel fm=new fileNameModel();
        // local picture path
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        String urls= FileUtil.getURL(fileName);
        fm.setFilePath(urls);
        fm.setId(params.getParameter("id"));
        fm.setNames(params.getParameter("uname"));
        fm.setPwd(params.getParameter("pwd"));


        try {
            FileUtil.uploadFile(file.getBytes(), urls, fileName);

        } catch (Exception e) {
            // TODO: handle exception
        }
        //返回json
        return JSON.toJSONString(fm);
    }

}

